import axios from 'axios'
import {useUserStore} from '@/stores/user'
import router from '@/router';

import { ElMessage } from 'element-plus';
const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 30000
})

// axios请求拦截器
instance.interceptors.request.use(config => {
    // 1. 从pinia获取token数据
    const userStore = useUserStore()
    // 2. 按照后端的要求拼接token数据
    const token = userStore.userInfo.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  }, e => Promise.reject(e))
// axios响应拦截器
instance.interceptors.response.use(
    res => {
      return res.data
    },
    e => {
      // 确保响应存在
      const userStore = useUserStore()
      if (e.response) {
        if (e.response.status === 401) {
          userStore.clearUser()
          router.push('/login')
        }
        ElMessage.warning(e.response.data.message)
      } else {
        // 处理网络错误或其他非 HTTP 错误
        ElMessage.error('网络错误或服务器无响应')
      }
      return Promise.reject(e)
    }
  )
  //导航前置守卫
  // router.beforeEach((to,from,next)=>{
  //   const userStore = useUserStore()
  //   if(to.path=='/member'&&!userStore.userInfo?.token){
  //     next('/login')
  //   }else{
  //     next()
  //   }
  // })

export default instance